var WF = {};
var L10n_inp_title = lang.label('inp_title');
var L10n_inp_layout = lang.label('inp_layout');
var L10n_inp_slideshow = lang.label('inp_slideshow');
var L10n_inp_slideshow_is_slideshow_description = lang.label('inp_slideshow_is_slideshow_description');
var L10n_inp_slideshow_interval_description = lang.label('inp_slideshow_interval_description');
var L10n_inp_slideshow_interval_invalid = lang.label('inp_slideshow_interval_invalid');
var L10n_inp_slideshow_number_should_greater_1 = lang.label('inp_slideshow_number_should_greater_1');
var L10n_inp_fit = lang.label('inp_fit');
var L10n_inp_fit_tip = lang.label('inp_fit_tip');
var L10n_inp_on = lang.label('on');
var L10n_inp_off  = lang.label('off');
var L10n_btn_cancel  = lang.label('btn_cancel');
var L10n_btn_save = lang.label('btn_save');

// Tab Slide Show global variable
var timeOutSlideShow,
    isSlideShowOn = 0,
    arrSlideShow = new Array(),
    arrSlideShowPageName = new Array(),
    arrIntervalSlideShow = new Array(),
    indexActiveSlideShow = 0,
    elUITimer = $('slide_show_btn'),
    elLabelTabSlideShow = $$('.label_tab_slide_show')[0];

WF.util = {
    Button: function(){
        var dButton = $$('.ui-button');
        dButton.each(function(item,i){
            item.addEvents({
                'mouseover': function(e){
                    item.addClass('hover');
                },
                'mouseout': function(e){
                    item.removeClass('hover');
                },
                'mousedown': function(e){
                    item.addClass('pressed');
                },
                'mouseup': function(e){
                    item.removeClass('pressed');
                },
                'focus': function(e){
                    item.addClass('focus');
                },
                'blur': function(e){
                    item.removeClass('focus');
                }
            });
        });
    },
    startSlideShow: function(){
    	//Step 1 : initial slide show value
    	isSlideShowOn = 0;
    	arrSlideShow = new Array();
    	arrIntervalSlideShow = new Array();
    	
    	//Step 2 : analyze which tab is in slide show
    	WF.util.doTimerSlideShow();
        if(arrSlideShow.length > 1){ // If slide show number > 1
        	if(elUITimer.hasClass('start')){
        		elUITimer.removeClass('start');
        	}
        	elUITimer.addClass('stop');
        	elLabelTabSlideShow.set('html',lang.label('tab_slide_show_stop'));
            WF.util.animateSlideShow();
            elUITimer.removeEvents('click');
            elUITimer.addEvent('click',function(event){
            	event.preventDefault();
            	// Fix IE7 hover bug
            	event.target.blur();
            	WF.util.stopSlideShow();
            });
        }else{
        	var option = {
                type: '0', //0 error, 1 warning, 2 info
                description: lang.label('inp_slideshow_number_should_greater_1'),
                name: 'slideShowNumberNoMoreThan1',
                close: true
            };
            wfc_message.fireEvent('message',option);
        }
    },
    stopSlideShow:function(){
    	if(elUITimer.hasClass('stop')){
    		elUITimer.removeClass('stop');
    	}
    	elUITimer.addClass('play');
    	elLabelTabSlideShow.set('html',lang.label('tab_slide_show_play'));
    	//elUITimer.set('class','play');
        clearTimeout(timeOutSlideShow);
        elUITimer.removeEvents('click');
        indexActiveSlideShow--;
        if(indexActiveSlideShow < 0){
        	indexActiveSlideShow = arrSlideShow.length;
        }
        elUITimer.addEvent('click',function(event){
        	event.preventDefault();
        	// Fix IE7 hover bug
        	event.target.blur();
        	WF.util.startSlideShow();
        });
    },
    animateSlideShow: function (){
    	if(arrSlideShow.length > 1){
	        if(indexActiveSlideShow >= arrSlideShow.length){
	            indexActiveSlideShow = 0;
	        }
	        wfc_mainScreen.checkActive(arrSlideShow[indexActiveSlideShow]);
	        if(wfc_qa_test){
	        	clientLogger.debug('[Tab Rotate] Tab['+arrSlideShowPageName[indexActiveSlideShow]+'] actived!');
	        }
	        timeOutSlideShow = setTimeout("WF.util.animateSlideShow()",parseInt(arrIntervalSlideShow[indexActiveSlideShow],10)*1000);
	        indexActiveSlideShow++;
    	}
    },
    // analyze tab data attribute
    // and sort out arrSlideShow which tab is in slide show
    doTimerSlideShow : function(){
        if (!isSlideShowOn){
            isSlideShowOn = 1;
            
            // for calculate indexActiveSlideShow from lastTab
            var lastTabPageNumber = Cookie.get("lastTab",{path: wf_cookie_path});
            //Step 1: Get Array tab element
            var arrElTab = $$('.tab_title');
            for(var x=0,y=arrElTab.length; x < y; x++){
                // Step 2 : analyze each tab data in data attribute
            	var strJsonTabData = arrElTab[x].get('data');
                if(strJsonTabData != ""){
                	jsonTabData = JSON.decode(strJsonTabData);
                    if(jsonTabData.isSlideShow == 1){ // if isSlideShow == 1
                    	if(lastTabPageNumber == jsonTabData.pageNumber){
                    		indexActiveSlideShow = x;
                    	}
                    	var intLengthArrSlideShow = arrSlideShow.length;
                    	// save arrSlideShow & arrIntervalSlideShow to global variable
                    	arrSlideShow[intLengthArrSlideShow] = jsonTabData.pageNumber; //save pageNumber to arrSlideShow array
                    	if(wfc_qa_test){
                    		arrSlideShowPageName[intLengthArrSlideShow] = jsonTabData.name;
                    	}
                    	arrIntervalSlideShow[intLengthArrSlideShow] = jsonTabData.intIntervalSlideShow; //save interval to arrIntervalSlideShow array
                    }
                }
            }
        }
    },
    TableButton: function(){
        var tableButton = $$('.ui-grid .func li div');
        tableButton.each(function(item,i){
            item.addEvents({
                'mouseover': function(e){
                    item.addClass('hover');
                },
                'mouseout': function(e){
                    item.removeClass('hover');
                }
            });
        });
    },
    SaveUdata: function(refresh){
        var m = 0;
        var arrUdata = [];
        var dPage = this.GetCurrentPage();
        var dBox = $('canvas'+dPage.number).getElements('.box');
        for(var i=0,j=dBox.length;i<j;i++){
            var dWidget = dBox[i].getElements('.widget');
            for(var k=0,l=dWidget.length;k<l;k++){
                var data = JSON.decode(dWidget[k].getProperty('data'));
                arrUdata[m] = {
                    'modname':data.name,
                    'column':dBox[i].getProperty('position'),
                    'wid':data.wid,
                    'page':dPage.number,
                    'order':k+1,
                    'widget_key':data.widget_key
                };
                m++;
            }
        }
        if(refresh){
            var callback = function(){
                window.location.reload();
            };
        }
        else{
            var callback = gonull;
        }
        sendData(dbHandler, JSON.encode({act:'udata', pid:dPage.number, udata:arrUdata}), callback);
    },
    SavePdata: function(){
        var arrPdata = [];
        var dTab = $$('#tab_panel li');
        for(var i=0,j=dTab.length-1;i<j;i++)
        {
            if(dTab[i].getElement('.tab_title')!=null)
            {
                var data = JSON.decode(dTab[i].getElement('.tab_title').getProperty('data'));
                arrPdata[i] = {
                    'sqeuenceNumber': (i+1),
                    'pageName': data.name,
                    'layout': data.columns,
                    'icon': '',
                    'allowConfig': data.allowConfig,
                    'allowClose': data.allowClose,
                    'fixedColumn': data.fixedColumn,
                    'eventCode': data.eventCode,
                    'pageNumber': data.pageNumber,
                    'boxWidth': data.boxWidth,
                    'autoFit': parseInt(data.autoFit,10),
                    'isSlideShow': parseInt(data.isSlideShow,10),
                    'intIntervalSlideShow': parseInt(data.intIntervalSlideShow,10),
                    'container_id': wfcid
                };
            }
        }
        sendData(dbHandler, JSON.encode({act:'pdata', pdata:arrPdata, cid: wfcid}), gonull);
    },
    GetCurrentPage: function(){
        if($$('#tab_panel .tab_box_selected').length>0){
            var dTarget = $$('#tab_panel .tab_box_selected')[0];
            var data = JSON.decode(dTarget.getElement('.tab_title').getProperty('data'));
            var dPage = {
                number: data.pageNumber,
                layout: data.columns,
                title: data.name,
                autoFit: data.autoFit,
                isSlideShow: data.isSlideShow,
                intIntervalSlideShow: data.intIntervalSlideShow
            };
            return dPage;
        }
    },
    GetPageNumber: function(){
        var data = JSON.encode({act:'getPageNumberPlusOne'});
        sendData(dbHandler, data, function(responseText){
            responseText = JSON.decode(responseText[0]);
            if(responseText && responseText.response && responseText.response == 'OK'){
                var pagenumber = responseText.result.page_number_plus_one;
                WF.util.TabSetting(true,pagenumber);
            }
        }.bind(this));
        /*
        var dNumber = 1;
        var numberArray = [];
        var dTab = $$('#tab_panel li');
        for(var i=0,j=dTab.length-1;i<j;i++)
        {
            if(dTab[i].getElement('.tab_title')!=null)
            {
                var data = JSON.decode(dTab[i].getElement('.tab_title').getProperty('data'));
                numberArray.push(data.pageNumber);
            }
        }
        numberArray.sort(sortTabsNumbers);
        if(numberArray.length>0){
            dNumber = numberArray[0]+1;
        }
        return dNumber;
        */
    },
    getWidgetsOfTab: function(pageNumber, getWidgetsOfTabCallback){
        var callback = function(widgets){
            var udataArray = Array();
            if (widgets[0]){
                udataArray = JSON.decode(widgets[0]).result;
                if (udataArray !== ""){
                    return getWidgetsOfTabCallback(udataArray);
                }
            }
            return getWidgetsOfTabCallback(udataArray);
        };
        sendData(dbHandler, JSON.encode({act:'getModule', pid:pageNumber,async:false}), callback, {pid:pageNumber});
    },
    TabSetting: function(isNew,pagenumber){
        WF.util.stopSlideShow();
        var HTML = [
            '<div id="layout_setting">',
            '   <div class="hd">',
            '       <div class="first row clearfix">',
            '           <div class="title">'+L10n_inp_title+'</div>',
            '           <div class="content"><input type="text" value="" id="layout_title" maxlength="64"></div>',
            '       </div>',
            '       <div class="row clearfix">',
            '           <div class="title">'+L10n_inp_layout+'</div>',
            '           <div class="content list">',
            '               <div class="listrow clearfix">',
            '                   <div class="item">',
            '                       <input type="radio" name="layout_type" value="1" id="layout_type_1" checked="checked"><label for="layout_type_1"><img src="img/default/layout_1.png"></label>',
            '                   </div>',
            '               </div>',
            '               <div class="listrow clearfix">',
            '                   <div class="item">',
            '                       <input type="radio" name="layout_type" value="2" id="layout_type_2"><label for="layout_type_2"><img src="img/default/layout_2.png"></label>',
            '                   </div>',
            '                   <div class="item">',
            '                       <input type="radio" name="layout_type" value="3" id="layout_type_3"><label for="layout_type_3"><img src="img/default/layout_3.png"></label>',
            '                   </div>',
            '                   <div class="item">',
            '                       <input type="radio" name="layout_type" value="4" id="layout_type_4"><label for="layout_type_4"><img src="img/default/layout_4.png"></label>',
            '                   </div>',
            '                   <div class="item">',
            '                       <input type="radio" name="layout_type" value="8" id="layout_type_8"><label for="layout_type_8"><img src="img/default/layout_8.png"></label>',
            '                   </div>',
            '               </div>',
            '               <div class="listrow clearfix">',
            '                   <div class="item">',
            '                       <input type="radio" name="layout_type" value="5" id="layout_type_5"><label for="layout_type_5"><img src="img/default/layout_5.png"></label>',
            '                   </div>',
            '                   <div class="item">',
            '                       <input type="radio" name="layout_type" value="6" id="layout_type_6"><label for="layout_type_6"><img src="img/default/layout_6.png"></label>',
            '                   </div>',
            '                   <div class="item">',
            '                       <input type="radio" name="layout_type" value="7" id="layout_type_7"><label for="layout_type_7"><img src="img/default/layout_7.png"></label>',
            '                   </div>',
            '                   <div class="item">',
            '                       <input type="radio" name="layout_type" value="9" id="layout_type_9"><label for="layout_type_9"><img src="img/default/layout_9.png"></label>',
            '                   </div>',
            '               </div>',
            '           </div>',
            '       </div>',
            '       <div class="row clearfix">',
            '           <div class="title">'+L10n_inp_slideshow+'</div>',
            '           <div class="content list">',
            '               <div class="listrow clearfix">',
            '                   <div class="content"><input type="checkbox" value="1" name="layout_is_slideshow" id="layout_is_slideshow" checked="checked">'+L10n_inp_slideshow_is_slideshow_description+'</div>',
            '               </div>',
            '               <div class="listrow clearfix">',
            '                   <div class="content blockSlideshowIntervalDescription">'+L10n_inp_slideshow_interval_description.substitute({'input_type_textbox':'<input type="text" id="layout_slideshow_interval" value="10" size="2" />'})+'</div>',
            '               </div>',
            '           </div>',
            '       </div>',
            '       <div class="row clearfix">',
            '           <div class="title">'+L10n_inp_fit+'<div id="autofit_hint" class="annnotation_hint"></div><div id="autofit_tip" class="annnotation_tip hide">'+L10n_inp_fit_tip+'</div></div>',
            '           <div class="content">',
            '               <input type="radio" name="auto_fit" value="1" id="autofit_on" checked="checked"><label for="autofit_on">'+L10n_inp_on+'</label>',
            '               <input type="radio" name="auto_fit" value="0" id="autofit_off"><label for="autofit_off">'+L10n_inp_off+'</label>',
            '           </div>',
            '       </div>',
            '   </div>',
            '   <div class="bd clearfix">',
            '       <div id="cancel_layout" class="ui-button clearfix"><div class="left"></div><div class="mid">'+L10n_btn_cancel+'</div></div>',
            '       <div id="save_layout" class="ui-button clearfix"><div class="left"></div><div class="mid">'+L10n_btn_save+'</div></div>',
            '   </div>',
            '</div>'
        ].join('');
        /**
         * Use intMaxPageNumberOfPrefixSuffixPage and intArrElTabLength to determine intNextTabNumber
         * EX : if intMaxPageNumberOfPrefixSuffixPage is empty => intNextTabNumber = intArrElTabLength + 1
         *      if intMaxPageNumberOfPrefixSuffixPage > 0 => intNextTabNumber = intMaxPageNumberOfPrefixSuffixPage + 1
         */
        var getNextTabNumber = function(){
        	var intReturnNumber = 1, //default
        	    intMaxPageNumberOfPrefixSuffixPage = 0, //default
        	    strPageName, // EX : Page 1 / Page_1 / MyPage / 第 1 頁
        	    strPageNameWithoutPrefixSuffixPage,  // EX : Page 1=>1 / Page_1=>1 / MyPage=>null / 第 1 頁=>1
        	    intPageNumber,  // EX : Page 1=>1 / Page_1=>1 / MyPage=>null / 第 1 頁=>1
                arrElTab = $$('.tab_title'), //Step 1: Get Array tab element
                intArrElTabLength = arrElTab.length;
            //Step 2: Find the max number from tab with prefix [Page ]
            // EX : [Tab XXX][Page 21][Page 1][Tab YYY] => intMaxPageNumberOfPrefixSuffixPage = 21
        	// EX : [第 1 頁][MyPage][第 22 頁][MyPage2] =>  intMaxPageNumberOfPrefixSuffixPage = 22
            for(var x=0; x < intArrElTabLength; x++){
                // analyze each tab data in data attribute
            	var strJsonTabData = arrElTab[x].get('data');
                if(strJsonTabData != ""){
                	jsonTabData = JSON.decode(strJsonTabData);
                	strPageName = jsonTabData.name;
                	// Step : check is strPageName if WGF new Page format
                	// EX [Page 1] => true
                	// EX [Page     1] => true
                	// EX [Page_1] => true
                	// EX [Page_____1] => true
                	// EX [第 1 頁] => true
                	// EX [第     1     頁] => true
                	// EX [第____1 頁] => true
                	// EX [MyPage] => false
                	// EX [My Tab] => false
                	if(strPageName.substr(0, lang.labelText("upperpage").length) == lang.labelText("upperpage") && (lang.labelText("page_number").length > 0 ? (strPageName.substr(lang.labelText("page_number").length*-1) == lang.labelText("page_number")) : true)){
                		//Step : eliminate prefix
                		// EX : [第 1 頁] => [ 1 頁] 
                		// EX : [Page 1 ] => [ 1 ] 
                		strPageNameWithoutPrefixSuffixPage = strPageName.substr(lang.labelText("upperpage").length);
                		//Step : eliminate suffix
                		// EX : [ 1 頁] => [ 1 ] 
                		// EX : [ 1 ] => [ 1 ] 
                		if(lang.labelText("page_number").length > 0){
                			strPageNameWithoutPrefixSuffixPage = strPageNameWithoutPrefixSuffixPage.substr(0, strPageNameWithoutPrefixSuffixPage.length-lang.labelText("page_number").length);
                		}
                		// trim space 
                		strPageNameWithoutPrefixSuffixPage = strPageNameWithoutPrefixSuffixPage.replace(/^\s+|\s+$/g,"");
                		// left trim symbol [_]
                		strPageNameWithoutPrefixSuffixPage = strPageNameWithoutPrefixSuffixPage.replace(/^_+/,"");
                		intPageNumber = parseInt(strPageNameWithoutPrefixSuffixPage,10);
                		if(intMaxPageNumberOfPrefixSuffixPage < intPageNumber){
                			intMaxPageNumberOfPrefixSuffixPage = intPageNumber;
                		}
                	}
                }
            }
            if(intMaxPageNumberOfPrefixSuffixPage > 0){
            	intReturnNumber = intMaxPageNumberOfPrefixSuffixPage + 1;
            }else{
            	intReturnNumber = intArrElTabLength + 1;
            }
            return intReturnNumber;
        };
        var currenPage = WF.util.GetCurrentPage();
        if(isNew){           
        	var arrTab = $$('.tab_title');
            if(arrTab.length>= tabLimit){
                wfc_error_msg(lang.label('not_more_tabs')+tabLimit+lang.label('not_more_tabs2'));
                return;
            }
            var modalTitle = lang.label('new_tab');
            // Get New Tab Number
            //var intNextTabNumber = arrTab.length + 1;
            var intNextTabNumber = getNextTabNumber();
            var inputTitle = lang.labelText("upperpage") + ' ' + intNextTabNumber + ' ' + lang.label("page_number");
        }else{
            var modalTitle = lang.label('tab_setting');
            if(wfc_loc_pageName){
                var inputTitle = TM_ProductLang.labelText(currenPage.title);
            }
            else{
                var inputTitle = currenPage.title;
            }
        }
        var height = this.iframeModaloffsetY();
        var options = {
            id: 'modalTabSetting',
            title: modalTitle,
            content: HTML,
            width: 'auto',
            height: 'auto',
            eventPosition: height,
            callBack: function(){
                WF.util.Button();
                WF.util.fixIELabelBug();
                var el_layout_is_slideshow = $('layout_is_slideshow'),
                    el_layout_slideshow_interval = $('layout_slideshow_interval');
                if(!isNew){
                    $('layout_type_'+currenPage.layout).set('checked',true);
                    if(currenPage.autoFit!='1'){
                        $('autofit_off').set('checked',true);
                    }
                    if(currenPage.isSlideShow !== undefined && currenPage.isSlideShow == '0'){
                    	el_layout_is_slideshow.set('checked',false);
                    }else{
                        el_layout_is_slideshow.set('checked',true);
                    }
                    if(currenPage.intIntervalSlideShow){
                    	el_layout_slideshow_interval.set('value',currenPage.intIntervalSlideShow);
                    }else{
                        el_layout_slideshow_interval.set('value',10); //default
                }
                }
                var dTitle = $('layout_title');
                dTitle.set('value',inputTitle);
                //dTitle.select();
                //new Fx.Scroll(window).toTop();
                var errormsg = '';
                $('save_layout').addEvent('click',function(event){
                    var dLayout = $$('#layout_setting input[name=layout_type]:checked')[0].value,
                        dAutoFit = $$('#layout_setting input[name=auto_fit]:checked')[0].value,
                        finalTitle = dTitle.get('value'),
                        layout_is_slideshow_checked = $$('#layout_setting input[name=layout_is_slideshow]:checked'),
                        isSlideShow = layout_is_slideshow_checked[0] !== undefined && layout_is_slideshow_checked[0].value ? 1 : 0,
                        errormsg = '';
                        //el_layout_slideshow_interval = $('layout_slideshow_interval');
                    if(el_layout_slideshow_interval.get('value') == ""){
                    	var elErrorMessage = $$('.error_message')[0];
                    	if(elErrorMessage !== undefined){
                    		elErrorMessage.destroy();
                    	}
                    	el_layout_slideshow_interval.focus();
                		//alert(L10n_inp_slideshow_interval_invalid);
                    	errormsg = new Element('div',{'class':'error_message'}).inject($('layout_setting'),"top");
                        var msg = new WFMessage(errormsg);
                        var option = {
                            type: '0', //0: error, 1: warn, 2: info
                            description: L10n_inp_slideshow_interval_invalid
                        };
                        msg.fireEvent('message',option);
                    	return;
                    }else if(checknumber(el_layout_slideshow_interval)){
                    	var elErrorMessage = $$('.error_message')[0];
                    	if(elErrorMessage !== undefined){
                    		elErrorMessage.destroy();
                    	}
                    	intIntervalSlideShow = el_layout_slideshow_interval.get('value');
                    	if(intIntervalSlideShow < 5 || intIntervalSlideShow > 3600){
                    		//alert(L10n_inp_slideshow_interval_invalid);
                    		el_layout_slideshow_interval.focus();
                    		errormsg = new Element('div',{'class':'error_message'}).inject($('layout_setting'),"top");
                            var msg = new WFMessage(errormsg);
                            var option = {
                                type: '0', //0: error, 1: warn, 2: info
                                description: L10n_inp_slideshow_interval_invalid
                            };
                            msg.fireEvent('message',option);
                        	return;
                    	}
                    }else{
                    	var elErrorMessage = $$('.error_message')[0];
                    	if(elErrorMessage !== undefined){
                    		elErrorMessage.destroy();
                    	}
                    	//alert(L10n_inp_slideshow_interval_invalid);
                    	el_layout_slideshow_interval.focus();
                    	errormsg = new Element('div',{'class':'error_message'}).inject($('layout_setting'),"top");
                        var msg = new WFMessage(errormsg);
                        var option = {
                            type: '0', //0: error, 1: warn, 2: info
                            description: L10n_inp_slideshow_interval_invalid
                        };
                        msg.fireEvent('message',option);
                    	return;
                    }
                        
                        
                    if (!trimString(finalTitle)){
                        if (!errormsg){
                            errormsg = new Element('div',{'class':'error_message'}).inject($('layout_setting'),"top");
                            var msg = new WFMessage(errormsg);
                            var option = {
                                type: '0', //0: error, 1: warn, 2: info
                                description: lang.label('empty_title')
                            };
                            msg.fireEvent('message',option);
                        }
                        dTitle.focus();
                        return;
                    }

                    if(isNew){
                        wfc_mainScreen.addCanvas(finalTitle, dLayout, null, null, null, null, null, true, pagenumber, false, true, '',parseInt(dAutoFit,10),parseInt(isSlideShow,10),parseInt(intIntervalSlideShow,10));
                        this.layoutModal.close();
                        this.layoutModal = null;
                    }else{
                        WF.util.InitWidget(); //init widget title only tab edit
                        //save data in tab
                        var dTab = $$('#tab_panel .tab_box_selected .tab_title')[0];
                        var data = JSON.decode(dTab.getProperty('data'));
                        data.columns = dLayout;
                        data.autoFit = parseInt(dAutoFit,10);
                        data.name = finalTitle;
                        data.boxWidth = '';
                        data.isSlideShow = parseInt(isSlideShow,10);
                        data.intIntervalSlideShow = parseInt(intIntervalSlideShow,10);
                        dTab.set('data',JSON.encode(data));
                        dTab.set('html',htmlentities(finalTitle));
                        //save pdata
                        WF.util.SavePdata();
                        //alert(finalTitle+'_'+dLayout+'_'+dAutoFit);
                        var pageNumber = WF.util.GetCurrentPage();
                        wfc_layout[pageNumber.number].changeLayout(dLayout);
                        this.layoutModal.close();
                        this.layoutModal = null;
                        WF.util.RefreshWidgetTitleEllipsis();
                    }
                    window.fireEvent('tab_change');
                }.bind(this));
                
                var setDisbaledElLayoutIsSlideshowInterval = function(){
                	if(el_layout_is_slideshow.get('checked') == false){
                		el_layout_slideshow_interval.set('disabled', true);
                    }else{
                    	el_layout_slideshow_interval.set('disabled', false);
                    }
                }
                setDisbaledElLayoutIsSlideshowInterval();
                el_layout_is_slideshow.addEvent('click',function(event){
                	setDisbaledElLayoutIsSlideshowInterval();
                }.bind(this));
                $('cancel_layout').addEvent('click',function(event){
                    this.layoutModal.close();
                    this.layoutModal = null;
                }.bind(this));
                $('autofit_hint').addEvent('mouseover',function(event){
                    $('autofit_tip').removeClass("hide");
                }.bind(this));
                $('autofit_hint').addEvent('mouseout',function(event){
                    $('autofit_tip').addClass("hide");
                }.bind(this));
            }.bind(this)
        };
        this.layoutModal = new WFModal(options);
        this.layoutModal.fireEvent('onComplete',this);
    },
    ShowAddWidget : function(){
        $$('#add_widgets_btn').addClass("add_widget_button");
    },
    HideAddWidget : function(){
        $$('#add_widgets_btn').addClass("no_add_widget_button");
    },
    NewWidget : function(widgets){
        var newWidgetObject = function(widget){
            var objNewWidget = " return new "+widget.modname +" ("+widget.column+","+widget.wid+"," +
                 widget.showMin+"," +widget.showClose+","+widget.showSetting+"," +
                 widget.showHelp+"," + widget.allowDrag+"," +widget.UniqueCss+"," +
                 widget.page+","+widget.order+",'"+widget.widget_key+"');";
            var objNewWidgetFn = new Function(objNewWidget);
            modules[widget.wid] = objNewWidgetFn();
        };

        widgets.each(function(widget){
            newWidgetObject(widget);
        });
    },
    includeWidgetJS: function(widgets){
        var intAssetLoadedCount= 0;
        var arrTempWidgets = [];
        var isSuccess = false;
        pgWidgets += widgets.length;
        widgets.each(function(widget){
            if (window[widget.modname] == undefined && !arrTempWidgets.contains(widget.modname)){
                arrTempWidgets.push(widget.modname);
            }
        });
        
        if (arrTempWidgets.length === 0){
            WF.util.NewWidget(widgets);
            isSuccess = true;
        }else{
        	// Preload current tab widget needed L10N
        	langUtil.preloadL10NModuleByArrWidget(arrTempWidgets);
        	
            arrTempWidgets.each(function(widgetName){
				var widget_module = '/module.js';
				if(wfc_widget_compact === true)
				{
					widget_module = '/module-min.js';
				}				
                Asset.javascript(WF.util.getWidgetPath(widgetName) +"/"+ widgetName + widget_module , {
                    onload: function(){
                        if(!wfc_widget_list.contains(widgetName)){
                            wfc_widget_list.push(widgetName);
                            intAssetLoadedCount++;
                            if (intAssetLoadedCount === arrTempWidgets.length){
                                WF.util.NewWidget(widgets);
                                isSuccess = true;
                            }
                        }
                    }
                });
            });
        }
        return isSuccess;
    },
    HasNewWidget: function(){
        /*this.checkNewWidgetJSON = new WFRequest.JSON(
        {
            url:homeBase+"inc/widget_package_manager.php?"+ AddUrlParam(),
            method: 'post',
            async: false,
            timeout: ajaxTimeoutValue,
            data:JSON.encode({ "act":"check_new" }),
            urlEncoded: false,
            headers: {"Content-type": "application/json"}
        });
        this.checkNewWidgetJSON.send();
        return this.checkNewWidgetJSON.response.json.result > 0;*/
        return wpm_check_new;
    },
    HasNewSCM: function(){
        /*this.checkNewSCMJSON = new WFRequest.JSON(
        {
            url:homeBase+"inc/widget_package_manager.php?"+ AddUrlParam(),
            method: 'post',
            async: false,
            timeout: ajaxTimeoutValue_update_widgetPool,
            data:JSON.encode({ "act":"check_new_scm" }),
            urlEncoded: false,
            headers: {"Content-type": "application/json"}
        });
        this.checkNewSCMJSON.send();
        if(this.checkNewSCMJSON.response && this.checkNewSCMJSON.response.json && this.checkNewSCMJSON.response.json.result == "0"){*/
	    if( wpm_check_new_scm ){
	    	if( wpm_check_new_scm.progress == 1 && wpm_check_new_scm.version_check_result == 0 ){
		        //show message
	            var option = {
	                type: '2',
	                description: lang.labelText('update_scm'),
	                close: true,
	                button: lang.label('update_btn_update_widget'),
	                containers: ['dashBoard', 'mainConsole'],
	                callback: function(){
	                    //create modal
	                    var HTML = [
	                        '<div>',
	                        '    <div class="hd">',
	                        '        <div class="update_widget_info">'+lang.label('updating_scm')+'</div>',
	                        '        <div class="update_widget">',
	                        '            <img src="img/default/loading_02.gif">',
	                        '        </div>',
	                        '    </div>',
	                        '</div>'
	                    ].join('');
	                    var option = {
	                        id: 'modalSCMUpdate',
	                        title: '',
	                        content: HTML,
	                        width: '500px',
	                        showTitle: false,
	                        callBack: function(){
	                            //request status
	                            var data = 'module=modSCloud&taskAction=UpdateSCM&user_name='+userID;
	                            //show success
	                            var onSuccess = function(response){
	                                var data = JSON.decode(response);
	                                var HTML_err = [
	                                    '          <div>',
	                                    '             <div class="hd">',
	                                    '                 <div class="fail_update_widget"></div>',
	                                    '                 <div class="fail_update_widget_info">'+lang.label('fail_update_widget')+'</div>',
	                                    '             </div>',
	                                    '             <div class="bd clearfix">',
	                                    '                 <div id="fail_update_btn" class="ui-button clearfix"><div class="left"></div><div class="mid">'+lang.label('btn_ok')+'</div></div>',
	                                    '             </div>',
	                                    '           </div>'
	                                ].join('');
									var HTML_ok = [
										'          <div>',
										'             <div class="hd">',
										'                 <div id="successfully_update_widget" class="successfully_update_widget"></div>',
										'                 <div id="successfully_update_widget_info" class="successfully_update_widget_info">'+lang.label("update_reload_logout")+'</div>',
										'             </div>',
										'             <div class="bd clearfix">',
										'                 <div id="successfully_update_btn" class="ui-button clearfix"><div class="left"></div><div class="mid">'+lang.label('btn_ok')+'</div></div>',
										'             </div>',
										'           </div>'
									].join('');
	                                if(data && data.DocumentElement){
	                                    if(data.DocumentElement.Result == '0'){
											$$('#modalSCMUpdate .modalContent').set('html',HTML_ok);
	                                    }
										else{
	                                        $$('#modalSCMUpdate .modalContent').set('html',HTML_err);
	                                        if(data.DocumentElement.Message){
										        $$('#modalSCMUpdate .modalContent .fail_update_widget_info').set('html',data.DocumentElement.Message);
										    }
	                                    }
	                                }
	                                WF.util.Button();
	                                $$('#modalSCMUpdate #fail_update_btn').addEvent('click',function(){
	                                    this.updateSCM.close();
	                                }.bind(this));
	                                $$('#modalSCMUpdate #successfully_update_btn').addEvent('click',function(){
	                                    //window.location.reload();
										parent.top.location.replace(wfc_widget_product_logon_page);
	                                }.bind(this));
	                            }.bind(this);
	                            var onFailure = function(){
	                                var HTML = [
	                                    '          <div>',
	                                    '             <div class="hd">',
	                                    '                 <div class="fail_update_widget"></div>',
	                                    '                 <div class="fail_update_widget_info">'+lang.label('fail_update_widget')+'</div>',
	                                    '             </div>',
	                                    '             <div class="bd clearfix">',
	                                    '                 <div id="fail_update_btn" class="ui-button clearfix"><div class="left"></div><div class="mid">'+lang.label('btn_ok')+'</div></div>',
	                                    '             </div>',
	                                    '           </div>'
	                                ].join('');
	                                $$('#modalSCMUpdate .modalContent').set('html',HTML);
	                                WF.util.Button();
	                                $$('#modalSCMUpdate #fail_update_btn').addEvent('click',function(){
	                                    this.updateSCM.close();
	                                }.bind(this));
	                            }.bind(this);
	                            wfc_ProxyObj.fetch(data, {useJSON:false,async:true,timeout: ajaxTimeoutValue_update_widgetPool}, {onSuccess:onSuccess, onFailure:onFailure});
	                        }.bind(this)
	                    };
	                    this.updateSCM = new WFModal(option);
	                }.bind(this)
	            };
                wfc_message.fireEvent('message',option);		        
            }else if( wpm_check_new_scm.version_error_code == 2 ){
                //show message
                wfc_message.fireEvent('message',{
                    type: '2',
                    description: lang.labelText('update_scm_patch_required', [wpm_check_new_scm.patch_min]),
                    close: true
                });				
            }
    	}
    },
    TabDrag: function(){
        var dTab = $('ui-tab').getElements('li');
        var bindEvent = function(event){
            if(event.rightClick){
                return;
            }
            dTab = $('ui-tab').getElements('li');
            if (dTab.length == 2){
                return;
            }
            var lastTab = dTab[dTab.length-2].get('id');
            var clickTab = this.get('id');
            if(lastTab==clickTab){
                lastTab = dTab[dTab.length-3].get('id');
            }
            WF.util.stopSlideShow();
            var tab = this;
            tempDragTab = new Element('li', {'class':tab.get('class'),'html':tab.get('html'),'styles':{'width':tab.getSize().x+1,'display':'block','top':tab.getPosition().y,'left':tab.getPosition().x,'position':'absolute'}}).inject(tab,'before');
            tempTab = new Element('li', {'class':'temp','styles':{'width':tab.getSize().x-2,'height':tab.getSize().y-1}}).inject(tab,'before');

            tab.setStyle('display','none');
            var tabDrag = new Drag.Move(tempDragTab, {
                'droppables': dTab,
                onDrag: function(element){
                    if(element.setCapture){
                        element.setCapture();
                    }
                    document.onmouseup = function(){
                        if(element.releaseCapture) {
                            element.releaseCapture();
                        }
                    };

                    if(this.enterTab && (this.enterTab.id == lastTab)){
                        if(element.getPosition().x>(this.enterTab.getPosition().x+this.enterTab.getSize().x/2)){
                            tempTab.inject(this.enterTab,'after');
                        }
                    }
                },
                onEnter: function(element, overed){
                    this.enterTab = overed;
                    tempTab.inject(overed,'before');
                },
                onLeave: function(element, overed){
                },
                onDrop: function(element, overed, event){
                    document.onmouseup = null;
                    tab.setStyles({'position':'static','display':'block'}).inject(tempTab,'before');
                    tempTab.destroy();
                    tempDragTab.destroy();
                    var data = JSON.decode(tab.getElement('.tab_title').getProperty('data'));
                    wfc_mainScreen.checkActive(data.pageNumber);
                    //save data
                    WF.util.SavePdata();
                    window.fireEvent('tab_change');
                },
                onCancel: function(){
                    tab.setStyles({'position':'static','display':'block'});
                    tempTab.destroy();
                    tempDragTab.destroy();
                    var data = JSON.decode(tab.getElement('.tab_title').getProperty('data'));
                    wfc_mainScreen.checkActive(data.pageNumber);
                    window.fireEvent('tab_change');
                }
            });
            tabDrag.start(event);
        };
        var tabLength = 0;
        for(var i=0,j=dTab.length-1;i<j;i++)
        {
            dTab[i].removeEvents('mousedown');
            dTab[i].addEvent('mousedown', bindEvent);
            /*
            Check the Tab element to prevent the js error form any possibility operations.
            */
            if(dTab[i].getElement('.tab_close_btn')!=null)
            {
                tabLength = tabLength + dTab[i].getSize().x + 1;
                dTab[i].getElement('.tab_close_btn').removeClass('hide');
            }
        }
        if(dTab.length==2){
            $$('#ui-tab .tab_box_selected .tab_close_btn').addClass('hide');
        }
        else{
            $$('#ui-tab .tab_box_selected .tab_close_btn').removeClass('hide');
        }
        return tabLength;
    },
    DifferenceTime: function(time){
        var currentTime = new Date().getTime();
        var difference = (currentTime-time.toInt()) - (86400 * wfc_shownew_days* 1000);
        return difference;
    },
    getWidgetPath: function(widgetName){
        if (g_arrUserGeneratedInfoOfWidget[widgetName] == 1){
           return USER_GENERATED_WIDGET_DIR;
        }else{
           return modFolder;
        }
    },
    fixIELabelBug: function(){
        if(document.all && navigator.appVersion.indexOf("MSIE")>-1 && navigator.appVersion.indexOf("Windows")>-1){
            var a = document.getElementsByTagName("label");
            for(var i=0,j=a.length;i<j;i++){
                if(a[i].hasChildNodes() && a[i].childNodes.item(0).tagName == "IMG"){
                    a[i].childNodes.item(0).forid = a[i].htmlFor;
                    a[i].childNodes.item(0).onclick = function(){
                        var e = document.getElementById(this.forid);
                        switch(e.type){
                            case "radio": e.checked|=1;break;
                            case "checkbox": e.checked=!e.checked;break;
                            case "text": case "password": case "textarea": e.focus(); break;
                        }
                    }
                }
            }
        }
    },
    RefreshWidgetTitleEllipsis: function(WidgetHTMLTableElement){
        if(WidgetHTMLTableElement === undefined){
            var arrWidget = $$('#canvas'+wfc_mainScreen.currActive+' .layout .widget');
            for(var i=0,j=arrWidget.length;i<j;i++){
                var intLeftWith = $(arrWidget[i]).getElement('.hd .left').getSize().x;
                var intRightWidth = $(arrWidget[i]).getElement('.hd .right').getSize().x;
                var elIcon = $(arrWidget[i]).getElement('.hd .icon');
                var intIconWidth = elIcon.getSize().x;
                var intTitleWidth = $(arrWidget[i]).getSize().x-intLeftWith-intRightWidth-intIconWidth;
                //alert('intWidgetSize:'+$(arrWidget[i]).getSize().x+' intLeftWith:'+intLeftWith+' intRightWidth:'+intRightWidth+' intIconWidth:'+intIconWidth+' intTitleWidth:'+intTitleWidth);
                $(arrWidget[i]).getElement('.hd .title').set('styles',{'width':intTitleWidth});
            }
        }else{
            var intLeftWith = WidgetHTMLTableElement.getElement('.hd .left').getSize().x;
            var intRightWidth = WidgetHTMLTableElement.getElement('.hd .right').getSize().x;
            var elIcon = WidgetHTMLTableElement.getElement('.hd .icon');
            var intIconWidth = elIcon.getSize().x;
            var intTitleWidth = WidgetHTMLTableElement.getSize().x-intLeftWith-intRightWidth-intIconWidth;
            //alert('intWidgetSize:'+WidgetHTMLTableElement.getSize().x+' intLeftWith:'+intLeftWith+' intRightWidth:'+intRightWidth+' intIconWidth:'+intIconWidth+' intTitleWidth:'+intTitleWidth);
            WidgetHTMLTableElement.getElement('.hd .title').set('styles',{'width':intTitleWidth});
        }
    },
    InitWidget: function(WidgetHTMLTableElement){
        if(WidgetHTMLTableElement === undefined){
            //before resize layout, set widget title width to default width and widgetContent width
            var arrWidget = $$('#canvas'+wfc_mainScreen.currActive+' .layout .widget');
            for(var i=0,j=arrWidget.length;i<j;i++){
                //reset widgetContent width to current box
                WF.util.setWidgetContentWidth($(arrWidget[i]));
                //reset widgte title to default width
                $(arrWidget[i]).getElement('.hd .title').set('styles',{'width':intWidgetTitleEllipsisDefaultWidth});
            }
        }else{
            //reset widgetContent width to current box
            WF.util.setWidgetContentWidth(WidgetHTMLTableElement);
            //reset widgte title to default width
            WidgetHTMLTableElement.getElement('.hd .title').set('styles',{'width':intWidgetTitleEllipsisDefaultWidth});
        }
    },
    setWidgetContentWidth: function(WidgetHTMLTableElement){
        //reset widgetContent width to current box
        var widgetContent = WidgetHTMLTableElement.getElement('.widgetContent');
        var widgetContentMaxWidth = widgetContent.getParent('.box').getSize().x-16;
        if(widgetContentMaxWidth && widgetContentMaxWidth > 0){
            widgetContent.setStyle('width', widgetContentMaxWidth);
        }        
    },
    iframeModaloffsetY: function(){
        var height = null;
        if(wf_iframe_id && parent.document.getElementById(wf_iframe_id)){
            return wfc_iframe_modal_top;
        }else{
            return height;
        }
    },
    isEmptyObject: function(ob){
        for(var i in ob){
           if(ob.hasOwnProperty(i)){
               return false;
           }
       }
       return true;
    },
    setIFrameHeight: function(){
        //reset iframe height
        if(top.frames.length>0){
            var obj = parent.document.getElementById(wf_iframe_id);
            if(obj){
                obj.height = wfc_iframe_minHeight;
                var wfHeight = window.document.body.scrollHeight;
                if (wfHeight > wfc_iframe_minHeight){
                    obj.height = wfHeight;
                }
            }
        }
    },
    findNextBoxForWidgets: function(boxNumber, arrOriginalWidgets, addWidgetNumber){
        var arrBoxSequence = [];
        var arrWidgetNumberOfBox = new Array(boxNumber);
        var arrAddWidgetNumberOfBox = new Array(boxNumber);
        for(var index = 0; index < boxNumber;index++){
            arrWidgetNumberOfBox[index] = 0;
            arrAddWidgetNumberOfBox[index] = 0;
        }

        //record widget number in each box
        if(arrOriginalWidgets){
            arrOriginalWidgets.each(function(widget,index){
                arrWidgetNumberOfBox[widget.column]++;
            });
        }else{
            arrOriginalWidgets = [];
    }
        //find box sequence
        while(addWidgetNumber--){
            var nextBox = arrWidgetNumberOfBox.indexOf(arrWidgetNumberOfBox.min());
            arrBoxSequence.push(nextBox);
            arrWidgetNumberOfBox[nextBox]++;
            arrAddWidgetNumberOfBox[nextBox]++;
    }

        if(arrOriginalWidgets){
            arrOriginalWidgets.each(function(widget){
                widget.order += arrAddWidgetNumberOfBox[widget.column];
            });
        }

        var objFindNextBoxResult = new Object();
        objFindNextBoxResult.arrBoxSequence = arrBoxSequence;
        objFindNextBoxResult.arrUpdatedOriginalUdata = arrOriginalWidgets;
        objFindNextBoxResult.arrAddWidgetNumberOfBox = arrAddWidgetNumberOfBox;
        arrWidgetNumberOfBox = null;

        return objFindNextBoxResult;
    },
    getBoxNumberOfLayout: function(layoutType){
        if(layoutType === "1"){
            return 1;
        }else if(layoutType === "2"){
            return 2;
        }else if(layoutType === "3"){
            return 3;
        }else if(layoutType === "4"){
            return 3;
        }else if(layoutType === "5"){
            return 3;
        }else if(layoutType === "6"){
            return 4;
        }else if(layoutType === "7"){
            return 4;
        }else if(layoutType === "8"){
            return 5;
        }else if(layoutType === "9"){
            return 5;
        }
    }
};

WF.module = {
    TabSetting: function(dModule){
        dModule.addEvents({
            'mouseover': function(event){
                this.addClass('hover');
            },
            'mouseout': function(event){
                this.removeClass('hover');
            },
            'click': function(event){
                event.preventDefault();
                WF.util.TabSetting(false, null);
            }
        });
        if (!wfconf_edit_tab_setting){
            dModule.addClass("no_edit_tab_button");
        }
    },
    NewTab: function(dModule){
        dModule.addEvent('click', function(event){
            event.preventDefault();
            WF.util.GetPageNumber();
        });

       if (!wfconf_add_tab_setting){
            dModule.addClass("no_add_tab_button");
        }
    },
    Window: function(dModule){
        if (!wfconf_default_menu){
            $('ui-tab').set('styles',{'display':'none'});
        }
        WF.util.Button();
        var pageLoad = 0;
        dModule.addEvent('widget_load',function(widgeInfo){
            var currentPage = WF.util.GetCurrentPage().number;
            if(widgeInfo && widgeInfo.pageNumber && currentPage != widgeInfo.pageNumber){
                if(!isInArray(inCompleteTabs, widgeInfo.pageNumber)){
                    inCompleteTabs.push(widgeInfo.pageNumber);
                }
                return false;
            }
            calltime++;
            if((calltime === pgWidgets || pageLoad == currentPage) && intAddWidgetNumber === 0) {
                $$('#canvas'+wfc_mainScreen.currActive+' .layout').fireEvent('autofit');
                calltime = 0;
                pageLoad = currentPage;
                WF.util.RefreshWidgetTitleEllipsis();
            }else if (intAddWidgetNumber > 0 && calltime === intAddWidgetNumber){
                $$('#canvas'+wfc_mainScreen.currActive+' .layout').fireEvent('autofit');
                calltime = 0;
                intAddWidgetNumber = 0;
                pageLoad = currentPage;
                WF.util.RefreshWidgetTitleEllipsis();
            }
        });
        $$('#add_widgets_btn .mid div').set('html',lang.label('menu_title'));
        $$('#tab_setting_btn .mid div').set('html',lang.label('tab_setting'));
        
        // pool update check
        WF.util.HasNewSCM();        
        WF.module.UpdateWidgetPool.bind(this)(new WFWidgetPackageManager());
        WF.module.showConfigureWidgetAndWidgetComponentUpdateMessage(new WFWidgetPackageManager());


        if(WF.util.HasNewWidget()){
            $$('#add_widgets_btn .mid').addClass('new');
            $$('#add_widgets_btn .mid').set('id','add_widget_new');
        }
        dModule.addEvent('tab_change',function(event){
            var dTab = $('ui-tab');
            var dTabWidth = dTab.getSize().x;
            if (dTabWidth > 0){
                var tabLength = WF.util.TabDrag();
                var tabMarginLeft = $('tab_panel').getStyle('margin-left').toInt();
                $('tab_panel').setStyle('margin-left','0');
                dTab.addClass('scroll');
                var dContainer = dTab.getElement('.container');

                var dWrapper = dTab.getElement('.wrapper');
                dWrapper.setStyle('width', 'auto');
                dWrapper.getElement('.tab_panel').setStyle('width', 'auto');
                var dContainerWidth = dContainer.getSize().x;
                var dWrapperWidth = dWrapper.getSize().x;

                var buttonWidth = 80;//dContainerWidth - dWrapperWidth;(IE9 need 80)
                if( tabLength > dTabWidth-40){
                    dTab.addClass('scroll');
                    dWrapper.setStyle('width', dTabWidth-buttonWidth);
                    dWrapper.getElement('.tab_panel').setStyle('width', '9999px');
                    $('tab_panel').setStyle('margin-left',tabMarginLeft);
                }
                else{
                    dTab.removeClass('scroll');
                    dWrapper.setStyle('width', 'auto');
                    dWrapper.getElement('.tab_panel').setStyle('width', 'auto');
                }
            }
        });
        var winOldWidth = getWidth();
        dModule.addEvent('resize', function(event)
        {
            var resizeTimer;

            function fireTabChange()
			{
                if (!$chk($('add_widget')))
                {
                    window.fireEvent('tab_change');
                }
			}

            function fireResizeLayout(){
                wfc_layout.each(function(layout){
                    if(layout){
                        clearTimeout(layout.resizeLayoutTimer);
                        layout.resizeLayoutTimer = setTimeout(function(){layout.resizeLayout();}, 200);
                    }
                });
            }

            var winNewWidth = getWidth();

			if(winNewWidth != winOldWidth)
			{
				clearTimeout(resizeTimer);
				resizeTimer = setTimeout(fireTabChange, 500);
                fireResizeLayout();
			}
			winOldWidth = winNewWidth;

        });
        if(wf_product_header){
            $('product_header').set('html',wf_product_header_html);
        }
        if(wf_product_message){
            $('product_message').set('html',wf_product_message_html);
            $('product_message').set('styles',{'display':'block'});
        }
        if(wfc_customized_layout){
            var langName = lang.getLang();
            Asset.css(WP_WEBROOT_NO_SLASH+'/css/'+langName+'.css');
        }
    },
    AddWidget: function(dModule){
        dModule.addEvents({
            'mouseover': function(event){
                this.addClass('hover');
            },
            'mouseout': function(event){
                this.removeClass('hover');
            }
        });
        dModule.addEvent('click',function(event){
        	WF.util.stopSlideShow();
            event.preventDefault();
            //get wisgetList
            if (!widgetList){
                var myRequest = new Request({url: wfc_servercgi_widgetlist, method: 'post', async: false});
                myRequest.send();
            }

            var HTML = [
                '<div class="container">',
                '    <div class="hd">',
                '        <h2>'+lang.label('menu_title')+'</h2>',
                '    </div>',
                '    <div class="bd clearfix">',
                '        <table>',
                '            <tr>',
                '                <td class="category">',
                '                    <ul>',
                '                        <li><a href="#">'+lang.label('latest_widgets')+' (0)</a></li>',
                '                        <li><a href="#">'+lang.label('all_widgets')+' (0)</a></li>',
                '                    </ul>',
                '                </td>',
                '                <td class="content">',
                '                    <div class="widget_search clearfix">',
                '                        <input id="keyword" class="hint" type="text" size="45" maxlength="60" value="'+lang.label('keyword_hint')+'">',
                '                        <a  id="clear" class="clear" href="#"></a>',
                '                    </div>',
                '                    <div class="menu clearfix">',
                '                        <div class="pager">',
                '                            '+lang.label('Records')+': <span class="current_start">0</span> - <span class="current_end">0</span> / <span class="total">0</span> ',
                '                            <select class="select_pernumber">',
                '                                <option value="5">5</option>',
                '                                <option value="10">10</option>',
                '                                <option value="20">20</option>',
                '                                <option value="50">50</option>',
                '                            </select> '+lang.label('perpage'),
                '                        </div>',
                '                        <div class="changeview clearfix">',
                '                            <a href="#" class="list" title="'+lang.label('detailed_view')+'"></a>',
                '                            <a href="#" class="thumb select" title="'+lang.label('summary_view')+'"></a>',
                '                        </div>',
                '                    </div>',
                '                    <div class="listview">',
                '                    </div>',
                '                    <div class="thumbview">',
                '                    </div>',
                '                    <div class="paginator clearfix">',
                '                    </div>',
                '                    <div class="control clearfix">',
                '                        <div class="add ui-button clearfix disable"><div class="left"></div><div class="mid">'+lang.label('btn_add')+'</div></div>',
                '                        <div class="cancel ui-button clearfix"><div class="left"></div><div class="mid">'+L10n_btn_cancel+'</div></div>',
                '                        <div class="data"><span class="selected">0</span> '+lang.label('widgets_selected')+'</div>',
                '                    </div>',
                '                </td>',
                '            </tr>',
                '        </table>',
                '    </div>',
                '</div>'
            ].join('');
            $('page_header').set('styles',{'display':'none'});
            //$('page_body').set('styles',{'display':'none'});
            $('page_body').addClass('off');
            $('page_footer').set('styles',{'display':'none'});
            var objectAddWidget = new Element('div',{
                'html':HTML,
                'id':'add_widget'/*,
                'styles':{
                    'min-height': $(document).getScrollSize().y-25
                }*/
            }).inject($(document.body),'top');

            if (wfc_listWidgetNumber == 5){
                objectAddWidget.getElements('.select_pernumber option')[0].setProperty('selected', 'selected');
            }else if (wfc_listWidgetNumber == 10){
                objectAddWidget.getElements('.select_pernumber option')[1].setProperty('selected', 'selected');
            }else if (wfc_listWidgetNumber == 20){
                objectAddWidget.getElements('.select_pernumber option')[2].setProperty('selected', 'selected');
            }else{
                objectAddWidget.getElements('.select_pernumber option')[3].setProperty('selected', 'selected');
            }

            WF.util.Button();
            //init category
            var arrCategory;
            var arrCatList;
            var strPreKeyword;
            var strDefaultKeyword = lang.label('keyword_hint');
            var arrAddWidget = [];
            var initWidgetList = function(widgetList, strKeyword){
                if(!widgetList){
                    widgetList = [];
                }
                arrCategory = [];
                arrCatList = [];
                arrTempCatList = [];
                arrCategory['all'] = [];
                arrCategory['latest'] = [];
                arrCatList.push('all');
                arrCatList.push('latest');

                var strLowerCaseKeyword = strKeyword.toLowerCase();
                // arrWidgetNeedToPreloadL10N is the widgets will sent to backend and get the L10N
                var arrWidgetNeedToPreloadL10N = [];
                widgetList.each(function(widget, i){
                	arrWidgetNeedToPreloadL10N[arrWidgetNeedToPreloadL10N.length] = widget.name;
                });
                langUtil.preloadL10NModuleByArrWidget(arrWidgetNeedToPreloadL10N);
                
                widgetList.each(function(widget, i){
                   //read widget L10N
                    var widget_lang = window[widget.name+'_locLang'];
                    if(!widget_lang) {
	                    window[widget.name+'_locLang'] = new localLang(widget.name);
                    	modList.set(widget.name, window[widget.name+'_locLang'].label('title'));
                        widget_lang = window[widget.name+'_locLang'];
                    }
                    //filter by keyword
                    var strFilteredResult = (widget_lang.labelText('title')).toLowerCase().indexOf(strLowerCaseKeyword);
                    var widgetCategory = widget.category.split(',');
                    widgetCategory.each(function(category, j){
                        if(!$chk(arrCategory[category])){
                            arrCategory[category] = [];
                            arrTempCatList.push(category);
                        }

                        if(strKeyword == "" || strFilteredResult != -1){
                            arrCategory[category].push(widget);
                            var difference=WF.util.DifferenceTime(widget.lastupdate);
                            if(difference <0){
                                if (!$chk(arrCategory['latest'])){
                                    arrCategory['latest'] = [];
                                }
                                if (!$chk(arrCategory['latest'].contains(widget))){
                                    arrCategory['latest'].push(widget);
                                }
                            }
                            if (!$chk(arrCategory['all'].contains(widget))){
                                arrCategory['all'].push(widget);
                            }
                        }
                    });
                });
                arrTempCatList.sort();
                arrTempCatList.each(function(category, i){
                    arrCatList.push(category);
                });
                strPreKeyword = strKeyword;
            };
            initWidgetList(widgetList.widgets, "");
            //render category
            var dCategory = objectAddWidget.getElement('.category ul');
            var latestNumber = 0;
            var dCategoryMenu = [];
            var selectCategory = 'all';
            var selectView = 'thumbview';
            var selectPage = 1;
            var selectNumber = wfc_listWidgetNumber;
            var addWidgets = [];
            var selectWidget = 0;
            var msg = null;
            var reduceSizeForTitle = 375; // 230px left column + 110px padding + 10px checkbox + 15px star
            var reduceSizeForTitleDetail = 590; // 230px left column + 50px padding + 50px checkbox + 240px right columns + 20px star
            var imgWidth = 100;
            var starWidth = 20;
            var resizeDescLines = function(){
                if (!$chk($('add_widget')) || typeof objectAddWidget.getElement === 'undefined'){
                    return;
                }
                var containerSize = objectAddWidget.getElement('.container').getSize().x;
                var availWidthForTitle =  containerSize - reduceSizeForTitle;
                var availWidthForDesc = availWidthForTitle - imgWidth;
                objectAddWidget.getElements('.thumbview .mod-content div.hd h3 label').each(function(el){
                    el.setStyle('width','auto');
                    if (el.getSize().x > availWidthForTitle){
                        el.setStyle('width',availWidthForTitle + 'px');
                    }
                });
                objectAddWidget.getElements('.thumbview .mod-content .data div').each(function(el){
                    el.setStyle('width',availWidthForDesc + 'px');
                });
                availWidthForTitle = containerSize - reduceSizeForTitleDetail;
                objectAddWidget.getElements('td.content td span.title').each(function(el){
                    el.setStyle('width','auto');
                    el.getParent('div').setStyle('width',(availWidthForTitle + starWidth) + 'px');
                    if (el.getSize().x > availWidthForTitle){
                        el.setStyle('width',availWidthForTitle + 'px');
                    }
                });
            };
            var renderCategory = function(strSelectedCategoryId){
                if($chk(arrCategory['latest'])){
                    latestNumber = arrCategory['latest'].length;
                }
                var HTML = '<li><a id="latestCategory" href="#" name="latest">'+lang.label('latest_widgets')+' ('+latestNumber+')</a></li><li><a id="allCategory" href="#" name="all" class="selected">'+lang.label('all_widgets')+' ('+arrCategory['all'].length+')</a></li>';
                arrCatList.each(function(category, i){
                    if(!(category=='all'||category=='latest')){
                        HTML += '<li><a id="'+category+'" href="#" name="'+category+'">'+TM_ProductLang.labelText('category_'+category)+' ('+arrCategory[category].length+')</a></li>';
                    }
                });
                dCategory.set('html',HTML);

                if(strSelectedCategoryId != undefined){
                    $('allCategory').removeClass('selected');
                    $(''+strSelectedCategoryId+'').addClass('selected');
                }
                renderDatatable(selectCategory,selectView,selectPage,selectNumber);
                //bind click event
                dCategoryMenu = dCategory.getElements('li a');
                dCategoryMenu.addEvent('click',function(event){
                    event.preventDefault();
                    dCategoryMenu.each(function(item,i){
                        item.removeClass('selected');
                    });
                    this.addClass('selected');
                    selectCategory = this.get('name');
                    var bindPage = 1;
                    renderDatatable(selectCategory,selectView,bindPage,selectNumber);
                });
            };
            //render datatable
            var renderDatatable = function(category, view, page, number){
                //set default data
                if(!$chk(category)){
                    category = 'all';
                }
                if(!$chk(view)){
                    view = 'thumbview';
                }
                if(!$chk(page)){
                    page = 1;
                }
                if(!$chk(number)){
                    number = wfc_listWidgetNumber;
                }
                objectAddWidget.getElement('.listview').set('styles',{'display':'none'});
                objectAddWidget.getElement('.thumbview').set('styles',{'display':'none'});
                objectAddWidget.getElement('.'+view).set('styles',{'display':'block'});
                if(!$chk(arrCategory[category])){
                    arrCategory[category] = [];
                }
                var dListview = objectAddWidget.getElement('.listview');
                var dThumbview = objectAddWidget.getElement('.thumbview');
                var dListHTML = [
                    '                            <tr>',
                    '                                <th class="box"><input type="checkbox" class="select_all"></th>',
                    '                                <th class="name"><span>'+lang.label('widget_name')+'</span></th>',
                    '                                <th class="cate"><span>'+lang.label('category')+'</span></th>',
                    '                                <th class="update"><span>'+lang.label('last_updated')+'</span></th>',
                    '                            </tr>'
                ].join('');
                var dThumbHTML = '';
                //render paginator
                var total = arrCategory[category].length;
                var pager = Math.ceil(total/number);
                if(page>pager){
                    page = pager;
                    selectPage = pager;
                }
                if(page==0){
                    page = 1;
                    selectPage = 1;
                }
                var start = (page-1)*number;
                var end = start + number;
                if(end>total){
                    end = total
                }
                var begin = 0;
                if(total != 0){
                    var begin = start+1;
                }
                objectAddWidget.getElement('.current_start').set('html',begin);
                objectAddWidget.getElement('.current_end').set('html',end);
                objectAddWidget.getElement('.total').set('html',total);
                var dPaginator = objectAddWidget.getElement('.paginator');
                var dPaginatorHTML = '<a href="#" class="pre" id="btn_pre">< '+lang.label('previous')+'</a>';

                if(pager<11){
                    for(var i=0,j=pager;i<j;i++){
                        var pagenumber = i+1;
                        if((page-1) == i){
                            dPaginatorHTML += '<a href="#" class="page select" page="'+pagenumber+'" id="page_'+pagenumber+'">'+pagenumber+'</a>';
                        }
                        else{
                            dPaginatorHTML += '<a href="#" class="page" page="'+pagenumber+'" id="page_'+pagenumber+'">'+pagenumber+'</a>';
                        }
                    }
                }
                else{
                    if(page>5 && page < pager-4){
                        dPaginatorHTML += '<a href="#" class="page" page="1" id="page_1">1</a><div class="blank">...</div>';
                        for(var i=0,j=7;i<j;i++){
                            var pagenumber = page-3+i;
                            if(page == pagenumber){
                                dPaginatorHTML += '<a href="#" class="page select" page="'+pagenumber+'" id="page_'+pagenumber+'">'+pagenumber+'</a>';
                            }
                            else{
                                dPaginatorHTML += '<a href="#" class="page" page="'+pagenumber+'" id="page_'+pagenumber+'">'+pagenumber+'</a>';
                            }
                        }
                        dPaginatorHTML += '<div class="blank">...</div><a href="#" class="page" page="'+pager+'" id="page_'+pager+'">'+pager+'</a>';
                    }
                    else if(page<=5){
                        for(var i=0,j=8;i<j;i++){
                            var pagenumber = i+1;
                            if(page == pagenumber){
                                dPaginatorHTML += '<a href="#" class="page select" page="'+pagenumber+'" id="page_'+pagenumber+'">'+pagenumber+'</a>';
                            }
                            else{
                                dPaginatorHTML += '<a href="#" class="page" page="'+pagenumber+'" id="page_'+pagenumber+'">'+pagenumber+'</a>';
                            }
                        }
                        dPaginatorHTML += '<div class="blank">...</div><a href="#" class="page" page="'+pager+'" id="page_'+pager+'">'+pager+'</a>';
                    }
                    else{
                        dPaginatorHTML += '<a href="#" class="page" page="1" id="page_1">1</a><div class="blank">...</div>';
                        for(var i=0,j=8;i<j;i++){
                            var pagenumber = pager-7+i;
                            if(page == pagenumber){
                                dPaginatorHTML += '<a href="#" class="page select" page="'+pagenumber+'" id="page_'+pagenumber+'">'+pagenumber+'</a>';
                            }
                            else{
                                dPaginatorHTML += '<a href="#" class="page" page="'+pagenumber+'" id="page_'+pagenumber+'">'+pagenumber+'</a>';
                            }
                        }

                    }
                }

                dPaginatorHTML += '<a href="#" class="next" id="btn_next">'+lang.label('next')+' ></a>';
                dPaginator.set('html',dPaginatorHTML);

                if (pager <= 1){
                    objectAddWidget.getElement('.pre').addClass('disable');
                    objectAddWidget.getElement('.next').addClass('disable');
                }else{
                    if (selectPage == 1){
                        objectAddWidget.getElement('.pre').addClass('disable');
                    }

                    if (selectPage == pager){
                        objectAddWidget.getElement('.next').addClass('disable');
                    }
                }

                //render widget data
                for(var i=start,j=end;i<j;i++){
                    widget = arrCategory[category][i];

                    var widget_lang = window[widget.name+'_locLang'];
                    //lastupdate
                    var lastupdate = '';
                    var isNew = '';
                    var isAdd = '';
                    if($chk(widget.lastupdate)){
                        lastupdate = new Date(widget.lastupdate.toInt()).formatDate(lang.label("lastupdate_format"));
                    }
                    var difference=WF.util.DifferenceTime(widget.lastupdate);
                    if(difference <0){
                        isNew = 'new';
                    }

                    for(var index = 0; index < addWidgets.length; index++){
                        var widgetItem = addWidgets[index];
                        if (widgetItem.name == widget.name){
                            isAdd = 'checked="checked"';
                            break;
                        }
                    }
                    var categoryData = [];
                    var widgetCategory = widget.category.split(',');
                    widgetCategory.each(function(item,index){
                        categoryData.push(TM_ProductLang.labelText('category_'+item));
                    });
                    categoryData = categoryData.join(', ');
                    var listHTML = [
                        '                            <tr>',
                        '                                <td class="box"><input type="checkbox" class="checkbox" value="'+widget.modname+'" widget_key="'+htmlentities(widget.widget_key)+'" name="'+widget.name+'" param="'+htmlentities(widget.param)+'" '+isAdd+'></td>',
                        '                                <td class="'+isNew+'"><div><span class="title ellipsis">'+widget_lang.label('title')+'</span>'+((isNew)?'<span class="star"></span>':'')+'</div></td>',
                        '                                <td><div class="breakword">'+categoryData+'</div></td>',
                        '                                <td>'+lastupdate+'</td>',
                        '                            </tr>'
                    ].join('');
                    var checkboxNumber = i+1;
                    var langPath = lang.getLang();
                    var imagePath = WF.util.getWidgetPath(widget.name)+'/'+widget.name+'/img/';
                    if (widget.icon){
                        if (wfc_icon_L10N){
                            var defaultImgPath = imagePath+langPath+'/';
                        }else{
                            var defaultImgPath = imagePath;
                        }
                    }else{
                        var defaultImgPath = '';
                    }

                    if (widget.icon_preview){
                        if (wfc_icon_L10N){
                            var previewImgPath = imagePath+langPath+'/';
                        }else{
                            var previewImgPath = imagePath;
                        }
                    }else{
                        var previewImgPath = '';
                    }
                    var thumbHTML = [
                        '                        <div class="item">',
                        '                            <span class="x0"></span><span class="x1"><span class="x1a"></span></span><span class="x2"><span class="x2a"></span></span>',
                        '                            <div class="mod-content">',
                        '                                <div class="hd clearfix">',
                        '                                   <h3 class="'+isNew+'">',
                        '                                       <input id="add_widget_'+checkboxNumber+'" type="checkbox" class="checkbox" value="'+widget.modname+'" widget_key="'+htmlentities(widget.widget_key)+'" name="'+widget.name+'" param="'+htmlentities(widget.param)+'" '+isAdd+'>',
                        '                                       <label class="ellipsis" for="add_widget_'+checkboxNumber+'">'+widget_lang.label('title')+'</label>'+((isNew)?'<span class="star"></span>':''),
                        '                                   </h3>',
                        '                                </div>',
                        '                                <div class="bd">',
                        '                                    <table>',
                        '                                        <tr>',
                        '                                            <td class="image">',
                        '                                                 <img class="widgetlogo" src="'+defaultImgPath+widget.icon+'" preview="'+previewImgPath+widget.icon_preview+'">',
                        '                                            </td>',
                        '                                            </td>',
                        '                                            <td class="data">',
                        '                                                <div class="description">'+ widget_lang.label('description')+'</div>',
                        '                                                <div class="ellipsis">',
                        '                                                    <span class="title">' + lang.label('category_widget') + '</span><span class="tag">'+categoryData+'</span>',
                        '                                                </div>',
                        '                                                <div class="ellipsis">',
                        '                                                    <span class="title">' + lang.label('lastupdate_at') + '</span><span class="time">'+lastupdate+'</span>',
                        '                                                </div>',
                        '                                            </td>',
                        '                                        </tr>',
                        '                                    </table>',
                        '                                </div>',
                        '                                <div class="ft"></div>',
                        '                            </div>',
                        '                        </div>',
                    ].join('');
                    dListHTML += listHTML;
                    dThumbHTML += thumbHTML;
                };
                // widget logo mouseover preview layer
                var dPreviewHTML = ['<div class="preview-container">',
                                        '<div class="preview-layer">',
                                            '<div class="pre-hd">',
                                                '<div class="tl-corner"></div><span class="pointer"></span><div class="tr-corner"></div>',
                                            '</div>',
                                            '<div class="pre-bd">',
                                                '<img class="preview-img" src="' + WP_WEBROOT_NO_SLASH + '/theme/default/img/ajax-loader.gif" />',
                                            '</div>',
                                            '<div class="pre-ft">',
                                                '<div class="bl-corner"></div><span class="pointer"></span><div class="br-corner"></div>',
                                            '</div>',
                                        '</div>',
                                        '<div class="preview-underlay"></div>',
                                    '</div>',
                ].join('');
                dListview.set('html','<table>'+dListHTML+'</table>');
                dThumbHTML += dPreviewHTML
                dThumbview.set('html',dThumbHTML);

                //reset iframe height
                WF.util.setIFrameHeight();

                //bind paginator event
                objectAddWidget.getElements('.page').each(function(item, i){
                    item.addEvent('click',function(event){
                        event.preventDefault();
                        var preSelectedPage = objectAddWidget.getElement('.page.select').get('page').toInt();
                        selectPage = this.get('page').toInt();
                        if (preSelectedPage != selectPage){
                            renderDatatable(selectCategory, selectView, selectPage, selectNumber);
                        }
                    });
                });
                objectAddWidget.getElement('.pre').addEvent('click',function(event){
                    event.preventDefault();
                   if (!objectAddWidget.getElement('.pre').hasClass('disable')){
                       if(selectPage != 1){
                           selectPage--;
                       }
                       renderDatatable(selectCategory, selectView, selectPage, selectNumber);
                    }
                });
                objectAddWidget.getElement('.next').addEvent('click',function(event){
                    event.preventDefault();
                    if (!objectAddWidget.getElement('.next').hasClass('disable')){
                       if(selectPage != pager){
                            selectPage++;
                        }
                        renderDatatable(selectCategory, selectView, selectPage, selectNumber);
                    }
                });
                //bind select number
                objectAddWidget.getElements('.checkbox').each(function(item, i){
                    item.addEvent('click',function(event){
                        if(this.get('checked')){
                            if ((pgWidgets + selectWidget) < wfc_widgetLimit){
                                var objWidget = new Object();
                                objWidget.name = this.get('name');
                                objWidget.modname = this.get('value');
                                objWidget.widget_key = html_entity_decode(this.get('widget_key'));
                                objWidget.param = html_entity_decode(this.get('param'));
                                addWidgets.push(objWidget);
                                selectWidget++;
                            }else{
                                this.set('checked',false);
                                if ($$('#add_widget div[name="addWidgetNoMoreThan20"]').length == 0){
                                    var errormsg = new Element('div',{'class':'error_message'}).inject($('add_widget'),"top");
                                    msg = new WFMessage(errormsg);
                                    var option = {
                                        type: '0', //0 error, 1 warning, 2 info
                                        description: lang.label('widget_maximum_number_1')+wfc_widgetLimit+lang.label('widget_maximum_number_2'),
                                        name: 'addWidgetNoMoreThan20',
                                        close: true,
                                        reserveRoot: false
                                    };
                                    msg.fireEvent('message',option);
                                }
                            }
                        }
                        else{
                            if (msg){
                                msg.clear();
                            }
                            var removedItem = this.get('name');
                            for(var index = addWidgets.length -1; index >= 0; index--){
                                var widgetItem = addWidgets[index];
                                if (widgetItem.name == removedItem){
                                    addWidgets.splice(index, 1);
                                    break;
                                }
                            }
                            selectWidget--;
                        }
                        objectAddWidget.getElement('.add').removeClass('disable');
                        if(!selectWidget){
                            objectAddWidget.getElement('.add').addClass('disable');
                            objectAddWidget.getElement('.select_all').set('checked',false);
                        }
                        objectAddWidget.getElement('.control .selected').set('html',selectWidget);
                    });
                });
                objectAddWidget.getElement('.select_all').addEvent('click',function(event){
                    if(this.get('checked')){ //If select all checked
                            for(var i=0,items=objectAddWidget.getElements('.listview .checkbox'),j=items.length;i<j;i++){
                                var item = items[i];
                                if(!item.get('checked')){
                                    if ((pgWidgets + selectWidget) > (wfc_widgetLimit - 1)){
                                        if ($$('#add_widget div[name="addWidgetNoMoreThan20"]').length == 0){
                                            var errormsg = new Element('div',{'class':'error_message'}).inject($('add_widget'),"top");
                                            msg = new WFMessage(errormsg);
                                            var option = {
                                                type: '0', //0 error, 1 warning, 2 info
                                                description: lang.label('widget_maximum_number_1')+wfc_widgetLimit+lang.label('widget_maximum_number_2'),
                                                name: 'addWidgetNoMoreThan20',
                                                close: true,
                                                reserveRoot: false
                                            };
                                            msg.fireEvent('message',option);
                                        }
                                        break;
                                    }
                                    var objWidget = new Object();
                                    objWidget.name = item.get('name');
                                    objWidget.modname = item.get('value');
                                    objWidget.widget_key = html_entity_decode(item.get('widget_key'));
                                    objWidget.param = html_entity_decode(item.get('param'));
                                    item.set('checked',true);
                                    addWidgets.push(objWidget);
                                    selectWidget++;
                                }
                            }

                        }

                    else{
                        if (msg){
                            msg.clear();
                        }
                        objectAddWidget.getElements('.listview .checkbox').each(function(item, i){
                            if(item.get('checked')){
                                item.set('checked',false);

                                var removedItem = item.get('name');
                                for(var index = addWidgets.length -1; index >= 0; index--){
                                    var widgetItem = addWidgets[index];
                                    if (widgetItem.name == removedItem){
                                        addWidgets.splice(index, 1);
                                        break;
                                    }
                                }
                                selectWidget--;
                            }
                        });
                    }
                    objectAddWidget.getElement('.add').removeClass('disable');
                    if(!selectWidget){
                        objectAddWidget.getElement('.add').addClass('disable');
                    }
                    objectAddWidget.getElement('.control .selected').set('html',selectWidget);
                });
                //bind mouseover event to widget logo for preview.
                var previewCont = objectAddWidget.getElement('.content .thumbview .preview-container'),
                    imgCont = previewCont.getElement('.pre-bd'),
                    arrowOffsetUp = 12,
                    arrowOffsetDown = 9;
                objectAddWidget.getElements('.content .thumbview img.widgetlogo').each(function(el, index, context){
                    el.addEvents({
                        mouseover:function(e){
                            var dImg = $(this),
                                imgPos = dImg.getPosition(),
                                imgSize = dImg.getSize();

                            if(!dImg.getProperty('preview')){
                                return;
                            }
                            Asset.image(dImg.getProperty('preview'),{
                                onLoad:function(el){
                                    var viewHeight = (typeof document.documentElement.clientHeight !== 'undefined') ?
                                                    document.documentElement.clientHeight :
                                                    (typeof document.body.clientHeight !== 'undefined') ? document.body.clientHeight : window.innerHeight;
                                    imgCont.empty();
                                    el.inject(imgCont);
                                    var prevHeight = previewCont.getSize().y;
                                    if ((imgPos.y + imgSize.y + prevHeight) > viewHeight){
                                        if (prevHeight >= viewHeight || (imgPos.y - prevHeight) < 0){
                                            var topPos = (typeof document.documentElement.scrollTop !== 'undefined') ? document.documentElement.scrollTop : document.body.scrollTop;
                                            previewCont.setPosition({x:imgPos.x + imgSize.x , y:topPos});
                                        } else {
                                            previewCont.addClass('arrowdown');
                                            previewCont.setPosition({x:imgPos.x, y:imgPos.y - arrowOffsetDown - prevHeight});
                                        }
                                    } else {
                                        previewCont.addClass('arrowup');
                                        previewCont.setPosition({x:imgPos.x, y:imgPos.y + arrowOffsetUp + imgSize.y});
                                    }
                                    previewCont.setStyle('visibility','visible');
                                }
                            });
                        },
                        mouseout:function(e){
                            var targetImg = previewCont.getElement('.pre-bd img');
                            imgCont.empty();
                            var imgLoading = new Element('img',{'src':WP_WEBROOT_NO_SLASH + '/theme/default/img/ajax-loader.gif'}).inject(imgCont);
                            previewCont.setStyle('visibility','hidden');
                            previewCont.removeClass('arrowup');
                            previewCont.removeClass('arrowdown');
                        }
                    });
                });
                // set widths for each description lines
                resizeDescLines();
            };

            //init
            renderCategory();

            //bind event

            //widget search  event
            objectAddWidget.getElementById('keyword').addEvents({
                keyup: function(){
                    var strSelectedCategory = $$('.category ul li a.selected');
                    if (strPreKeyword == undefined || this.value != strPreKeyword){
                        initWidgetList(widgetList.widgets, this.value);
                        renderCategory(strSelectedCategory.get("id"));
                    }
                },
                focus: function(){
                    if (this.hasClass("hint")){
                        this.value = "";
                        this.removeClass("hint");
                    }
                },
                paste: function(){
                    var strSelectedCategory = $$('.category ul li a.selected');
                    if (strPreKeyword == undefined || this.value != strPreKeyword){
                        initWidgetList(widgetList.widgets, this.value);
                        renderCategory(strSelectedCategory.get("id"));
                    }
                }
            });
            objectAddWidget.getElementById('clear').addEvent('click',function(event){
                event.preventDefault();
                var objKeyword = objectAddWidget.getElementById('keyword');
                objKeyword.value = "";
                objKeyword.removeClass("hint");

                var objSelectedCategory = $$('.category ul li a.selected');
                if (strPreKeyword == undefined || objKeyword != strPreKeyword){
                    initWidgetList(widgetList.widgets, objKeyword.value);
                    renderCategory(objSelectedCategory.get("id"));
                }
                objKeyword.focus();
            });
            var closeAddWidget = function(){
                objectAddWidget.destroy();
                $(document).removeEvents('keydown');
                //window.removeEvent('resize', onResize);
            };
            var onResize = function(){
                resizeDescLines();
            /*
                objectAddWidget.set('styles',{'min-height': document.getCoordinates().height-25});
                objectAddWidget.set('styles',{'min-height': $(document).getScrollSize().y-25});
            */
            };
            var renderNewWidget = function(){
                wfc_widgetDataObj.fetchUData();
                wfc_widgetDataObj.fetchWData();
                intAddWidgetNumber = arrAddWidget.length;
                WF.util.includeWidgetJS(arrAddWidget);
                createGlobal(wfc_mainScreen.currActive);
            };
            objectAddWidget.getElement('.add').addEvent('click',function(event){
                if(selectWidget){
                    objectAddWidget.getElement('.add').removeEvents('click');
                    objectAddWidget.getElement('.add').addClass('disable');
                }else{
                    return;
                }
                var arrUdata = [];
                var arrWdata = [];
                var boxNumber = $$('#canvas'+wfc_mainScreen.currActive+' .layout .box').length;
                var number = 0;
                var getWidgetsOfTabCallback = function(arrOriginalWidgets){
                    var objFindNextBoxResult = WF.util.findNextBoxForWidgets(boxNumber, arrOriginalWidgets, addWidgets.length);
                addWidgets.each(function(widget,i){
                        var dOrder = objFindNextBoxResult.arrAddWidgetNumberOfBox[objFindNextBoxResult.arrBoxSequence[i]];
                        objFindNextBoxResult.arrAddWidgetNumberOfBox[objFindNextBoxResult.arrBoxSequence[i]]--;
                    arrUdata[i] = {
                        'modname':widget.modname,
                            'column':objFindNextBoxResult.arrBoxSequence[i],
                        'wid':pc,
                        'page':wfc_mainScreen.currActive,
                        'order':dOrder,
                        'widget_key':widget.widget_key
                    };
                    arrWdata[i] = {
                        'modname':widget.modname,
                        'wid':pc,
                        'data':'',
                        'pid':wfc_mainScreen.currActive,
                        'widget_key':widget.widget_key,
                        'param':widget.param
                    };

                    var objWidget = new Object();
                    objWidget.modname = widget.modname;
                        objWidget.column = objFindNextBoxResult.arrBoxSequence[i];
                    objWidget.wid = pc;
                    objWidget.page = wfc_mainScreen.currActive;
                    objWidget.order = dOrder;
                    objWidget.widget_key = widget.widget_key;
                    arrAddWidget.push(objWidget);
                    pc++;
                });
                var callBack = function(response){
                    var response = JSON.decode(response[0]);
                    closeAddWidget();
                    $('page_header').set('styles',{'display':'block'});
                    $('page_body').removeClass('off');
                    $('page_footer').set('styles',{'display':'block'});
                    window.fireEvent('tab_change');
                    window.fireEvent('resize');
                    if(!response.errcode){
                        renderNewWidget();
                    }
                    else{
                        var option = {
                            type: '0',
                            description: lang.label('errorcode_'+response.errcode),
                            close: true
                        };
                        wfc_message.fireEvent('message',option);
                    }
                };
                Cookie.set("lastID", pc-1, {path: wf_cookie_path});
                    sendData(dbHandler, JSON.encode({act:'addWidgets', pid:wfc_mainScreen.currActive, udata:arrUdata, wdata:arrWdata, updatedOriginalUdata:objFindNextBoxResult.arrUpdatedOriginalUdata}), callBack);
                    arrUdata = null;
                    arrWdata = null;
                    objFindNextBoxResult.arrBoxSequence = null;
                    objFindNextBoxResult.arrUpdatedOriginalUdata = null;
                    objFindNextBoxResult.arrAddWidgetNumberOfBox = null;
                    objFindNextBoxResult = null;
                };
                WF.util.getWidgetsOfTab(wfc_mainScreen.currActive, getWidgetsOfTabCallback.bind(this));
            });
            objectAddWidget.getElement('.cancel').addEvent('click',function(event){
                closeAddWidget();
                $('page_header').set('styles',{'display':'block'});
                $('page_body').removeClass('off');
                $('page_footer').set('styles',{'display':'block'});
                //reset iframe height
                WF.util.setIFrameHeight();
                
                window.fireEvent('tab_change');
                window.fireEvent('resize');
            });
            objectAddWidget.getElement('.select_pernumber').addEvent('change',function(event){
                selectNumber = this.get('value').toInt();
                renderDatatable(selectCategory, selectView, selectPage, selectNumber);
            });
            objectAddWidget.getElement('.list').addEvent('click',function(event){
                event.preventDefault();
                selectView = 'listview';
                objectAddWidget.getElement('.thumb').removeClass('select');
                objectAddWidget.getElement('.list').addClass('select');
                renderDatatable(selectCategory, selectView, selectPage, selectNumber);
            });
            objectAddWidget.getElement('.thumb').addEvent('click',function(event){
                event.preventDefault();
                selectView = 'thumbview';
                objectAddWidget.getElement('.list').removeClass('select');
                objectAddWidget.getElement('.thumb').addClass('select');
                renderDatatable(selectCategory, selectView, selectPage, selectNumber);
            });
            $(document).addEvent('keydown', function(event){
                if (event.key == 'esc') {
                    closeAddWidget();
                    $('page_header').set('styles',{'display':'block'});
                    $('page_body').removeClass('off');
                    $('page_footer').set('styles',{'display':'block'});
                    window.fireEvent('tab_change');
                    window.fireEvent('resize');
                }
            });
            window.addEvent('resize', onResize);
        });
    },
    UpdateWidgetPool: function(widgetPackageManager){
        if(wpm_check_widget){
            var option = {
                type: '2', //0 error, 1 warning, 2 info
                description: lang.label('update_widget'),
                button: lang.labelText('update_btn_update_widget'),
                close: true,
                containers: ['dashBoard'],
                callback: function(){
                    var updateWidgetPoolMessageHTML = [
                        '          <div>',
                        '             <div class="hd">',
                        '                 <div class="update_widget_info">'+lang.label("updating")+'</div>',
                        '                 <div class="update_widget">',
                        '                    <img src="img/default/loading_02.gif">',
                        '                 </div>',
                        '             </div>',
                        '           </div>'
                    ].join('');
                    var waitWidgetOption = {
                        id: 'modalUpdateWidgetPoolMessage',
                        title: "",
                        content: updateWidgetPoolMessageHTML,
                        width: '500px',
                        showTitle: false,
                        callBack: function(){
                            widgetPackageManager.updateWidget.bind(widgetPackageManager)(WF.module.UpdateWidgetPoolCallBack.bind(this));
                        }.bind(this)
                    };
                    this.updateWidgetLayout = new WFModal(waitWidgetOption);
                    this.updateWidgetLayout.fireEvent('onComplete',this);
                }
            };
            wfc_message.fireEvent('message',option);
        }
    },
    UpdateWidgetPoolCallBack : function(responseJSON){
        if((responseJSON.response.json === undefined && $('modalFailUpdateWidgetPoolMessage') === null) //if php timeout and modal message is existed
            || responseJSON.response.json === null){ //If php timeout
              responseJSON.response.json = {};
              responseJSON.response.json.errcode = 9999; //set errcode to 9999
        }
      if(responseJSON.response.json === undefined){
          return;
      }
      if(responseJSON.response != null && responseJSON.response.json.errcode == 0){
        var successfullyUpdateWidgetHTML = [
            '          <div>',
            '             <div class="hd">',
            '                 <div id="successfully_update_widget" class="successfully_update_widget"></div>',
            '                 <div id="successfully_update_widget_info" class="successfully_update_widget_info">'+lang.label("update_reload")+'</div>',
            '             </div>',
            '             <div class="bd clearfix">',
            '                 <div id="successfully_update_btn" class="ui-button clearfix"><div class="left"></div><div class="mid">'+lang.label('btn_ok')+'</div></div>',
            '             </div>',
            '           </div>'
        ].join('');

        var successfullyUpdateWidgetOption = {
            id: 'modalSuccessfullyUpdateWidgetPoolMessage',
            title: "",
            content: successfullyUpdateWidgetHTML,
            width: '500px',
            showTitle: false,
            callBack: function(){
                this.updateWidgetLayout.close();
                $$('#successfully_update_btn').addEvent('click',function(event){
                   window.location.reload();
                }.bind(this));
            }.bind(this)
        };
        this.successfullyUpdateWidgetLayout = new WFModal(successfullyUpdateWidgetOption);
        this.successfullyUpdateWidgetLayout.fireEvent('onComplete',this);
     }
     else
     {
       var failUpdateWidgetHTML = [
            '          <div>',
            '             <div class="hd">',
            '                 <div class="fail_update_widget"></div>',
            '                 <div class="fail_update_widget_info">'+lang.label("wpu_errorcode_"+responseJSON.response.json.errcode)+'</div>',
            '             </div>',
            '             <div class="bd clearfix">',
            '                 <div id="fail_update_btn" class="ui-button clearfix"><div class="left"></div><div class="mid">'+lang.label('btn_ok')+'</div></div>',
            '             </div>',
            '           </div>'
       ].join('');
       var failUpdateWidgetOption = {
            id: 'modalFailUpdateWidgetPoolMessage',
            title: "",
            content: failUpdateWidgetHTML,
            width: '500px',
            showTitle: false,
            callBack: function(){
                this.updateWidgetLayout.close();
                $$('#fail_update_btn').addEvent('click',function(event){
                   this.failUpdateWidgetLayout.close();
                }.bind(this));
            }.bind(this)
        };
        this.failUpdateWidgetLayout = new WFModal(failUpdateWidgetOption);
        this.failUpdateWidgetLayout.fireEvent('onComplete',this);
      }
    },
    showConfigureWidgetAndWidgetComponentUpdateMessage: function(widgetPackageManager){
       if(wpm_check_configure_widget_and_widget_component){
            var option = {
                type: '2', //0 error, 1 warning, 2 info
                description: lang.label('update_component'),
                button: lang.label('view'),
                close: true,
                containers: wfc_widget_component_and_configure_widget_message_container,
                callback: function(){
                    location.href = 'index.php?p=updateConfigureWidgetAndWidgetComponent'+ AddUrlParam();
                }
            };
            wfc_message.fireEvent('message',option);
        }
    },
    ViewConfigureWidgetAndWidgetComponent: function(dModule){
        var widgetPackageManager = new WFWidgetPackageManager();
        var response = widgetPackageManager.getConfigureWidgetAndWidgetComponent();
        var viewConfigureWidgetHTML = [
            '<table class="dataTable configureWidgetTable">',
            '    <thead>',
            '    <tr>',
            '        <th>'+lang.label('framework_type')+'</th>',
            '        <th class="current_version">'+lang.label('framework_version')+'</th>',
            '        <th class="status">'+lang.label('status')+'</th>',
            '        <th class="action">'+lang.label('action')+'</th>',
            '    </tr>',
            '    </thead>',
            '    <tbody>',
            '    </tbody>',
            '</table>'
        ].join('');
        this.configureWidgetContent = new Element('div',{'class':'ui-grid content configure_widget','html':viewConfigureWidgetHTML}).inject(dModule,'bottom');

        var dTable = dModule.getElement('.configureWidgetTable tbody');
        if(response && response.configure_widget){
            var dTR = new Element('tr');
            var status = response.configure_widget.update_status;

            this.configureWidgetStatus = new Element('td',{'html':lang.label('configuration_framework')}).inject(dTR,'bottom');
            new Element('td',{'html':response.configure_widget.current_version}).inject(dTR,'bottom');
            new Element('td',{'html':lang.label('status_'+status)}).inject(dTR,'bottom');

            if (status == 'enable'){
                this.configureWidgetBtn = new Element('td',{'html':'<div class="function clearfix"><div class="ui-button clearfix"><div class="left"></div><div class="mid">'+lang.label("btn_"+status)+' </div></div></div>'}).inject(dTR,'bottom');
                if(response.configure_widget.helper_url){
                    new Element('a',{'class':'status_update_info ui-link','href':response.configure_widget.helper_url,'html':lang.label("update_info")}).inject(this.configureWidgetBtn.getElement('.function'),'bottom');
                }
            }else if (status == 'update'){
                this.configureWidgetBtn = new Element('td',{'html':'<div class="function clearfix"><div class="ui-button clearfix"><div class="left"></div><div class="mid">'+lang.label("btn_"+status)+ ' ' +response.configure_widget.new_version+' </div></div></div>'}).inject(dTR,'bottom');
                if(response.configure_widget.helper_url){
                    new Element('a',{'class':'status_update_info ui-link','href':response.configure_widget.helper_url,'html':lang.label("update_info")}).inject(this.configureWidgetBtn.getElement('.function'),'bottom');
                }
            }else{
                this.configureWidgetBtn = new Element('td',{'html':''}).inject(dTR,'bottom');
            }
            dTR.inject(dTable,'bottom');

            if (this.configureWidgetBtn.getElement('.ui-button')){
                this.configureWidgetBtn.getElement('.ui-button').addEvent('click',function(){
                    WF.module.UpdateConfigureWidgetOrWidgetComponent(widgetPackageManager, "configure_widget", null);
                }.bind(this));
            }
        }

        var viewWidgetComponentHTML = [
            '<table class="dataTable widgetComponentTable">',
            '    <thead>',
            '    <tr>',
            '        <th>'+lang.label('management_type')+'</th>',
            '        <th class="current_version">'+lang.label('template_version')+'</th>',
            '        <th class="status">'+lang.label('status')+'</th>',
            '        <th class="action">'+lang.label('action')+'</th>',
            '    </tr>',
            '    </thead>',
            '    <tbody>',
            '    </tbody>',
            '</table>'
        ].join('');
        this.widgetComponentContent = new Element('div',{'class':'ui-grid content widget_component','html':viewWidgetComponentHTML}).inject(dModule,'bottom');

        var productLang = TM_ProductLang;
        if(response && response.widget_component){
            var widget_component = response.widget_component;
            if(widget_component){
                for(var i = 0; i < widget_component.length; i++){
                    if (widget_component[i].update_status == 'enable'){
                        productLang = new NewProductLang('modProduct');
                        break;
                    }
                }             
            }

            widget_component.each(function(item,index){
                var dTR = new Element('tr');
                this.WidgetComponentStatus = new Element('td',{'html':productLang.label('product_'+item.product_id)}).inject(dTR,'bottom');
                if(item.tip_content){
                    new Element('td',{'html':'<div class="clearfix"><span class="version_info">'+item.current_version+'</span><span class="tip_info" title="'+item.tip_content+'"></span></div>'}).inject(dTR,'bottom');
                }else{
                    new Element('td',{'html':'<div class="clearfix"><span class="version_info">'+item.current_version+'</span></div>'}).inject(dTR,'bottom');
                }
                new Element('td',{'html':lang.label('status_'+item.update_status)}).inject(dTR,'bottom');

                if (item.update_status == 'enable'){
                    this.widgetComponentBtn = new Element('td',{'html':'<div class="function clearfix"><div class="ui-button clearfix"><div class="left"></div><div class="mid">'+lang.label("btn_"+item.update_status)+' </div></div></div>'}).inject(dTR,'bottom');
                    if(item.helper_url){
                        new Element('a',{'class':'status_update_info ui-link','href':item.helper_url,'html':lang.label("update_info")}).inject(this.widgetComponentBtn.getElement('.function'),'bottom');
                    }
                }else if (item.update_status == 'update'){
                    this.widgetComponentBtn = new Element('td',{'html':'<div class="function clearfix"><div class="ui-button clearfix"><div class="left"></div><div class="mid">'+lang.label("btn_"+item.update_status)+ ' ' +item.new_version+' </div></div></div>'}).inject(dTR,'bottom');
                    if(item.helper_url){
                        new Element('a',{'class':'status_update_info ui-link','href':item.helper_url,'html':lang.label("update_info")}).inject(this.widgetComponentBtn.getElement('.function'),'bottom');
                    }
                }else{
                    this.widgetComponentBtn = new Element('td',{'html':''}).inject(dTR,'bottom');
                }
                var dTable = dModule.getElement('.widgetComponentTable tbody');
                dTR.inject(dTable,'bottom');
                if (this.widgetComponentBtn.getElement('.ui-button')){
                    this.widgetComponentBtn.getElement('.ui-button').addEvent('click',function(){
                        WF.module.UpdateConfigureWidgetOrWidgetComponent(widgetPackageManager, "widget_component", item.product_id);
                    }.bind(this));
                }
            }.bind(this));
        }

        $$('.status_update_info').addEvent('click',function(event){
            event.preventDefault();            
            window.open(homeBase+event.target.getAttribute('href'),"helpWindow","resizable=yes,scrollbars=1,width=600,height=600");
        });
        WF.util.Button();
    },
    UpdateConfigureWidgetOrWidgetComponent: function(widgetPackageManager, update_type, product_id){
        var updateMessageHTML = [
            '          <div>',
            '             <div class="hd">',
            '                 <div class="update_info">'+lang.label("updating")+'</div>',
            '                 <div class="update_loading">',
            '                    <img src="img/default/loading_02.gif">',
            '                 </div>',
            '             </div>',
            '           </div>'
        ].join('');

        var loadOption = {
            id: 'modalUpdateMessage',
            title: "",
            content: updateMessageHTML,
            width: '500px',
            showTitle: false,
            parentEl:$$('.template5')[0],
            callBack: function(){
                widgetPackageManager.updateConfigureWidgetOrWidgetComponent.bind(widgetPackageManager)(WF.module.UpdateConfigureWidgetOrWidgetCallBack.bind(this), update_type, product_id);
            }.bind(this)
        };
        this.updateConfigureWidgetOrWidgetComponentLayout = new WFModal(loadOption);
        this.updateConfigureWidgetOrWidgetComponentLayout.fireEvent('onComplete',this);
    },
    UpdateConfigureWidgetOrWidgetCallBack : function(responseJSON){
        if((responseJSON.response.json === undefined && $('modalFailUpdateMessage') === null) //if php timeout and modal message is existed
            || responseJSON.response.json === null){ //If php timeout
              responseJSON.response.json = {};
              responseJSON.response.json.errcode = 9999; //set errcode to 9999
        }
      if(responseJSON.response.json === undefined){
          return;
      }
      if(responseJSON.response != null && responseJSON.response.json.errcode == 0){
        var successfullyUpdateHTML = [
            '          <div>',
            '             <div class="hd">',
            '                 <div class="successfully_update"></div>',
            '                 <div class="successfully_update_info">'+lang.label("update_reload")+'</div>',
            '             </div>',
            '             <div class="bd clearfix">',
            '                 <div class="ui-button clearfix successfully_update_btn"><div class="left"></div><div class="mid">'+lang.label('btn_ok')+'</div></div>',
            '             </div>',
            '           </div>'
        ].join('');

        var successfullyUpdateOption = {
            id: 'modalSuccessfullyUpdateMessage',
            title: "",
            content: successfullyUpdateHTML,
            width: '500px',
            showTitle: false,
            parentEl:$$('.template5')[0],
            callBack: function(){
                this.updateConfigureWidgetOrWidgetComponentLayout.close();
                $$('.successfully_update_btn').addEvent('click',function(event){
                   window.location.reload();
                }.bind(this));
            }.bind(this)
        };
        this.successfullyUpdateConfigureWidgetOrWidgetComponentLayout = new WFModal(successfullyUpdateOption);
        this.successfullyUpdateConfigureWidgetOrWidgetComponentLayout.fireEvent('onComplete',this);
     }
     else
     {
       var failUpdateHTML = [
            '          <div>',
            '             <div class="hd">',
            '                 <div class="fail_update"></div>',
            '                 <div class="fail_update_info">'+lang.label("wpu_errorcode_"+responseJSON.response.json.errcode)+'</div>',
            '             </div>',
            '             <div class="bd clearfix">',
            '                 <div class="ui-button clearfix fail_update_btn"><div class="left"></div><div class="mid">'+lang.label('btn_ok')+'</div></div>',
            '             </div>',
            '           </div>'
       ].join('');
       var failUpdateOption = {
            id: 'modalFailUpdateMessage',
            title: "",
            content: failUpdateHTML,
            width: '500px',
            showTitle: false,
            parentEl:$$('.template5')[0],           
            callBack: function(){
                this.updateConfigureWidgetOrWidgetComponentLayout.close();
                $$('.fail_update_btn').addEvent('click',function(event){
                   this.failUpdateConfigureWidgetOrWidgetComponentLayout.close();
                }.bind(this));
            }.bind(this)
        };
        this.failUpdateConfigureWidgetOrWidgetComponentLayout = new WFModal(failUpdateOption);
        this.failUpdateConfigureWidgetOrWidgetComponentLayout.fireEvent('onComplete',this);
      }
      WF.util.Button();        
    },
    TabInit: function(dModule){
        var type = '';
        var dTarget = dModule.getElements('.tab_box');
        var width = 100;
        dTarget.each(function(item,i){
            item.addEvents({
                'mouseover': function(event){
                    this.addClass('hover');
                },
                'mouseout': function(event){
                    this.removeClass('hover');
                }
            });
        });
        function length(){
            var length = $$('#ui-tab .wrapper')[0].getSize().x;
            var dTab = $$('#tab_panel li');
            for(var i=0,j=dTab.length-1;i<j;i++){
                length -= (dTab[i].getSize().x+1);
            }
            return length;
        }
        function moveTab(){
            var marginLength = length();

            var value = $('tab_panel').getStyle('margin-left').toInt();
            if(type=='previous'){
                value = value+width;
            }
            else if(type=='next'){
                value = value-width;
            }
            if(value < 1){

				if(value < marginLength){
					$('tab_panel').setStyle('margin-left', marginLength);
				}
				else{
					$('tab_panel').setStyle('margin-left', value);
				}
            }
			else{
				value = 0;
				$('tab_panel').setStyle('margin-left', 0);
			}

        };
        dModule.getElement('.previous').addEvent('click',function(){
        	WF.util.stopSlideShow();
            type = 'previous';
            moveTab();
        });
        dModule.getElement('.next').addEvent('click',function(){
        	WF.util.stopSlideShow();
            type = 'next';
            moveTab();
        });
    },
    ServerList: function(dModule){
        dModule.addEvent('click',function(event){
        	WF.util.stopSlideShow();
            event.preventDefault();
            $('server_visib').blur();            
            new WFServerList();
        });
    },
    startSlideShowByDModule: function(dModule){
        dModule.addEvent('click',function(event){
        	event.preventDefault();
        	// Fix IE7 hover bug
        	event.target.blur();
        	WF.util.startSlideShow();
        });
        elLabelTabSlideShow.set('html',lang.label('tab_slide_show_play'));
        dModule.addEvent('mouseover',function(event){
        	dModule.addClass('hover');
        });
        dModule.addEvent('mouseout',function(event){
        	dModule.removeClass('hover');
        });
    }
};
